import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

// 导入样式和库
import  'font-awesome/css/font-awesome.min.css'
import axios from 'axios'
import qs from 'qs'
import {
    getCurDate,
    setSessionStorage,
    getSessionStorage,
    removeSessionStorage,
    setLocalStorage,
    getLocalStorage,
    removeLocalStorage
} from './common.js'

// 创建应用实例
const app = createApp(App)

// 配置axios
// axios.defaults.baseURL = 'http://192.168.137.201:8080/api'
axios.defaults.baseURL = 'http://localhost:8080/api'
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.headers.common['Accept'] = 'application/json'
// 全局属性
app.config.globalProperties.$axios = axios
app.config.globalProperties.$qs = qs
app.config.globalProperties.$getCurDate = getCurDate
app.config.globalProperties.$setSessionStorage = setSessionStorage
app.config.globalProperties.$getSessionStorage = getSessionStorage
app.config.globalProperties.$removeSessionStorage = removeSessionStorage
app.config.globalProperties.$setLocalStorage = setLocalStorage
app.config.globalProperties.$getLocalStorage = getLocalStorage
app.config.globalProperties.$removeLocalStorage = removeLocalStorage

// 路由守卫
router.beforeEach((to, from, next) => {
    // 从sessionStorage获取用户信息
    const user = sessionStorage.getItem('jwt')

    // 判断当前访问的页面是否需要登录（除了登录、注册、首页、商家列表、商家信息）
    if (
        !(
            to.path === '/' ||
            to.path === '/index' ||
            to.path === '/businessList' ||
            to.path === '/businessInfo' ||
            to.path === '/login' ||
            to.path === '/register'
        )
    ) {
        // 如果需要登录，但用户未登录
        if (user === null) {
            // 直接跳转到登录页
            next('/login')
            // 不需要location.reload()，Vue Router会处理导航
        } else {
            // 用户已登录，继续访问
            next()
        }
    } else {
        // 这些页面不需要登录，直接放行
        next()
    }
})



// 挂载应用
app.use(router)
app.mount('#app')